from subprocess import *
from enum import Enum
import re
import sys
import os
sys.path.append('../')
from goEnv import *
from goJudge import *
from utilities import *
from goAgent import GoAgent


cols='ABCDEFGHJKLMNOPQRST'


class Play_Gtp:
    def __init__(self, bot=None, handicap=0,opponent=["gnugo","--mode", "gtp"],output_sgf=None,our_color='b'):
        self.bot=bot
        self.handicap=0	#让子
        self.sgf=output_sgf	#记录棋局的sgf文件名
        self.ourColor=Player.black if our_color == 'b' else Player.white
        self.opColor=self.ourColor.other()
        self.dataFlow=Popen(opponent,shell=True,stdin=PIPE, stdout=PIPE,bufsize=0, universal_newlines=True)

    def cmd_to_op(self,command):
        self.dataFlow.stdin.write(command)

    def get_resp(self):
        succeed=False
        resp=""
        while not succeed:
            line = self.dataFlow.stdout.readline()
            if line[0]=='=':
                succeed=True
                line=line.strip()
                resp=re.sub('^= ?','',line)
        return resp

    def cmd_and_resp(self,command):
        self.cmd_to_op(command)
        return self.get_resp()

    def set_handicap(self):
        return None #暂时不实现让子

    def gtp_position_to_coords(self,gtp_position):
        col_str,row_str=gtp_position[0],gtp_position[1:]
        point = (int(row_str)-1, cols.find(col_str.upper()))
        return (point)

    def coords_to_gtp_position(self,point):
        col,row=(point[0],point[1])
        row_str=cols[row]
        print(col,row)
        return row_str+str(col+1)

    def play(self):
        board=GoBoard()
        os.system('cls')
        board.printBoard()
        whosTurn=Player.black
        player_next=whosTurn
        game_state=GameState.g_continue
        if self.bot is None: #手工下棋
            while game_state==GameState.g_continue:
                if whosTurn == Player.black:
                    #人工下棋没有判断落子合法性，过子，投降都暂时没提供功能
                    if sys.version_info.major==2: #python2 需要用raw_input
                        s=raw_input("请下棋:".decode('utf-8').encode('gbk')) #解决python2中文乱码问题
                    else:
                        s=input("请下棋:")
                    if s.lower() == 'resign':
                        #move=(-10,-10)
                        break
                    elif s.lower() == 'pass':
                        move=(-5,-5)
                    else:
                        move=self.gtp_position_to_coords(s)
                    commond='play black '+s
                    self.cmd_and_resp(commond+'\n')
                    [game_state,player_next]=GoJudge.NextState(whosTurn,move,board)
                    board.envUpdate(whosTurn,move)
                else:
                    commond="genmove white"
                    resp=self.cmd_and_resp(commond+'\n')
                    if resp.lower() == 'resign':
                        #move=(-10,-10)
                        break
                    elif resp.lower() == 'pass':
                        move=(-5,-5)
                    else:
                        move=self.gtp_position_to_coords(resp)
                    [game_state,player_next]=GoJudge.NextState(whosTurn,move,board)
                    board.envUpdate(whosTurn,move)
                if game_state!=GameState.g_over and game_state!=GameState.g_resign:
                    os.system('cls')
                    board.printBoard()
                    whosTurn=player_next
        else:
            while game_state==GameState.g_continue:
                if whosTurn == Player.black:
                    move=self.bot.chooseMove('R',board)
                    board.envUpdate(whosTurn,move)
                    if move ==(-5,-5):
                        s='pass'
                    elif move ==(-10,-10):
                        s='resign'
                    else:
                        s=self.coords_to_gtp_position(move)
                    commond='play black '+s
                    print(commond)
                    self.cmd_and_resp(commond+'\n')
                    [game_state,player_next]=GoJudge.NextState(whosTurn,move,board)
                    board.envUpdate(whosTurn,move)
                else:
                    commond="genmove white"
                    resp=self.cmd_and_resp(commond+'\n')
                    if resp.lower() == 'resign':
                        break
                    elif resp.lower() == 'pass':
                        move=(-5,-5)
                    else:
                        move=self.gtp_position_to_coords(resp)
                    [game_state,player_next]=GoJudge.NextState(whosTurn,move,board)
                    board.envUpdate(whosTurn,move)
                os.system('cls')
                board.printBoard()
                if game_state!=GameState.g_over and game_state!=GameState.g_resign:
                    whosTurn=player_next
                else:
                    print("Game Over!")


    def run(self):
        #初始化棋局
        self.cmd_and_resp("boardsize 19\n") #命令必须以\n结束
        self.set_handicap()
        #开始使用genmove和play命令下棋
        self.play()

if __name__ == "__main__":
    bot=GoAgent(Player.black)
    game = Play_Gtp(bot=bot)
    game.run()
